﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Application.Permisos.ServiceAgent;
using System.Windows.Forms;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Permisos
{
	public partial class ExpedicionViewModel
	{
		#region Private properties

		/// <summary>
		/// Tipos de fuente de riego.
		/// </summary>
		private List<RiegoFuente> _riegoFuentes;

		/// <summary>
		/// Tipo de fuente seleccionado.
		/// </summary>
		private RiegoFuente _riegoFuente;

		#endregion

		#region Public properties

		/// <summary>
		/// Tipos de fuente de riego.
		/// </summary>
		public List<RiegoFuente> RiegoFuentes
		{
			get
			{
				return _riegoFuentes;
			}
			private set
			{
				_riegoFuentes = value;
				if (_riegoFuentes != null)
					RaisePropertyChanged("RiegoFuentes");
			}
		}

		/// <summary>
		/// Tipo de fuente de riego seleccionado.
		/// </summary>
		public RiegoFuente RiegoFuente
		{
			get
			{
				return _riegoFuente;
			}
			private set
			{
				_riegoFuente = value;
				if (_riegoFuente != null)
					RaisePropertyChanged("RiegoFuente");
			}
		}

		#endregion

		#region Private methods

		private void LoadRiegoFuentes()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					using (PermisosModuleServiceWrapper service = new PermisosModuleServiceWrapper())
					{
						e.Result = service.FindRiegoFuentesByStatus(true);
					}
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						RiegoFuentes = e.Result as List<RiegoFuente>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		private void SetCurrentRiegoFuente(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null && bindingSource.Current != null)
				RiegoFuente = bindingSource.Current as RiegoFuente;
		}

		private void OnRiegoFuentesPropertyChanged()
		{
			_expedicionView.riegoFuenteBindingSource.DataSource = RiegoFuentes;
			_expedicionView.riegoFuenteBindingSource.CurrentChanged += SetCurrentRiegoFuente;
			SetCurrentRiegoFuente(_expedicionView.riegoFuenteBindingSource, new EventArgs());
		}

		private void OnRiegoFuentePropertyChanged()
		{
			// Actualizar el ID y GUID del tipo de fuente de riego
			// al permiso actual.
		}

		#endregion

	}
}
